(function() {
    'use strict';

    /**
     * @ngdoc directive
     * @name webApp.directive:uploader
     * @description
     * # uploader
     */
    angular.module('webApp')
        .directive('uploader', function() {
            return {
                restrict: 'E',
                templateUrl: "views/directives.uploader.html",
                scope: {
                    ownerId: '=',
                    ownerType: '=',
                    subOwnerId: '=', //所属子对象id
                    callBack: '&',
                    useType: "=",
                    maxSize: "=",
                },
                controller: ['$templateCache', '$rootScope', '$scope', '$compile', 'dataService', '$timeout', 'Upload', 'ERP_CONFIG', 'helper',
                    function($templateCache, $rootScope, $scope, $compile, dataService, $timeout, Upload, ERP_CONFIG, helper) {
                        $timeout(function() {
                            $scope.maxSize = $scope.maxSize || "2MB";
                            $scope.acceptType = $scope.useType ? $scope.useType.split(",") : [];
                            $scope.acceptTypex = _.map($scope.acceptType, function(a) {
                                return "." + a;
                            });
                            if ($scope.acceptTypex.length == 0) {
                                $scope.acceptTypeStr = "*";
                            } else {
                                $scope.acceptTypeStr = $scope.acceptTypex.join(",");
                            }
                        });


                        function allow(type) {
                            if (!$scope.useType) {
                                return true;
                            } else {
                                return $scope.acceptType.indexOf(type) != -1;
                            }
                        }



                        dataService.getToken(function(token) {
                            $scope.uploadPic = function(files,categoryId) {
                                if (files && files.length) {
                                    for (var i = 0; i < files.length; i++) {
                                        $scope.fileUpload(files[i], token,categoryId);
                                        // Upload.upload({ ..., data: { file: files[i] }, ... })...;
                                    }
                                }
                            }
                        });

                        $scope.fileUpload = function(file, token,categoryId) {
                            var filename = file.name.split('.');
                            if (!allow(filename[filename.length - 1])) {
                                $scope.errorMsg = "上传文件类型错误";
                            } else {
                                var data = {
                                    // content: file,
                                    // uuid: "img000" + random(),
                                    wxfile: file,
                                    token: token,
                                    categoryId:categoryId
                                };

                                var uploadUrl = ERP_CONFIG.uploadUrl + '/rest/v1/tcos/add';
                                file.upload = Upload.upload({
                                    url: uploadUrl,//
                                    data: {
                                        // content: file,
                                        // uuid: "img000" + random(),
                                        wxfile: file,
                                        token: token,
                                        categoryId:categoryId
                                    }
                                });

                                file.upload.then(function(response) {
                                    $timeout(function() {
                                        file.result = response.data;
                                        if (response.data.id) {
                                            if ($scope.callBack) {
                                                $scope.callBack();
                                            }
                                        } else {
                                            helper.myAlert("error" + response.data);
                                        }
                                    });
                                }, function(response) {
                                    if (response.status > 0)
                                        $scope.errorMsg = response.status + ': ' + response.data;
                                }, function(evt) {
                                    // Math.min is to fix IE which reports 200% sometimes
                                    file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
                                });
                            }
                        }
                    }
                ]
            }
        })
        .directive('wxuploader', function() {
            return {
                restrict: 'E',
                templateUrl: "views/directives.wxuploader.html",
                scope: {
                    wxappid: '=',
                    // ownerType: '=',
                    // subOwnerId: '=', //所属子对象id
                    callBack: '&',
                    useType: "=",
                    stype: "@",
                },
                controller: ['$templateCache', '$rootScope', '$scope', '$compile', 'dataService', '$timeout', 'Upload', 'ERP_CONFIG', 'helper',
                    function($templateCache, $rootScope, $scope, $compile, dataService, $timeout, Upload, ERP_CONFIG, helper) {
                        // console.log("11111",$scope.wxappid,$scope.useType);
                        $timeout(function() {
                            $scope.acceptType = $scope.useType ? $scope.useType.split(",") : [];
                            $scope.acceptTypex = _.map($scope.acceptType, function(a) {
                                return "." + a;
                            });
                            if ($scope.acceptTypex.length == 0) {
                                $scope.acceptTypeStr = "*";
                            } else {
                                $scope.acceptTypeStr = $scope.acceptTypex.join(",");
                            }
                        });


                        function allow(type) {
                            if (!$scope.useType) {
                                return true;
                            } else {
                                return $scope.acceptType.indexOf(type) != -1;
                            }
                        }



                        dataService.getToken(function(token) {
                            $scope.uploadPic = function(file) {
                                // console.log("file:", file);
                                var filename = file.name.split('.');

                                if (!allow(filename[filename.length - 1])) {
                                    $scope.errorMsg = "上传文件类型错误";
                                } else {
                                    var data = {
                                        authorizer_appid: $scope.wxappid,
                                        wxfile: file,
                                        token: token
                                    };
                                    // console.log("data", data);
                                    file.upload = Upload.upload({
                                        url: ERP_CONFIG.eprUrl + '/rest/v1/material/temp/add',
                                        data: data
                                    });

                                    file.upload.then(function(response) {
                                        $timeout(function() {
                                            console.log('response:', response.data);
                                            file.result = response.data;
                                            if (response.data.media_id) {
                                                if ($scope.callBack) {
                                                    $scope.callBack();
                                                }
                                                if ($scope.stype) {
                                                    rmAlert();
                                                }
                                            } else {
                                                helper.myAlert("error" + response.data.Msg);
                                            }
                                        });
                                    }, function(response) {
                                        if (response.status > 0)
                                            $scope.errorMsg = response.status + ': ' + response.data;
                                    }, function(evt) {
                                        // Math.min is to fix IE which reports 200% sometimes
                                        file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
                                    });
                                }
                            }
                        });

                    }
                ]
            }
        })
        .directive('wxGzhUrlUploader', function() {
            return {
                restrict: 'E',
                templateUrl: "views/directives.wxgzhurluploader.html",
                scope: {
                    wxappid: '=',
                    callBack: '&',
                    useType: "=",
                    // stype: "@",
                    type: "="
                },
                controller: ['$templateCache', '$rootScope', '$scope', '$compile', 'dataService', '$timeout', 'Upload', 'ERP_CONFIG', 'helper', 'sessionService',
                    function($templateCache, $rootScope, $scope, $compile, dataService, $timeout, Upload, ERP_CONFIG, helper, sessionService) {
                        // console.log("11111",$scope.wxappid,$scope.useType,$scope.type);
                        $timeout(function() {
                            $scope.acceptType = $scope.useType ? $scope.useType.split(",") : [];
                            $scope.acceptTypex = _.map($scope.acceptType, function(a) {
                                return "." + a;
                            });
                            if ($scope.acceptTypex.length == 0) {
                                $scope.acceptTypeStr = "*";
                            } else {
                                $scope.acceptTypeStr = $scope.acceptTypex.join(",");
                            }
                        });
                        $scope.showtype = 1;

                        function allow(type) {
                            if (!$scope.useType) {
                                return true;
                            } else {
                                return $scope.acceptType.indexOf(type) != -1;
                            }
                        }

                        dataService.getToken(function(token) {
                            $scope.uploadPic = function(file) {
                                var filename = file.name.split('.');
                                var url = ERP_CONFIG.eprUrl;
                                url = $scope.type == 'xiaoxi' ? url + '/rest/v1/material/uploadimg/add' : url + "/rest/v1/material/add_material/add";
                                if (!allow(filename[filename.length - 1])) {
                                    $scope.errorMsg = "上传文件类型错误";
                                } else {
                                    var data = {
                                        authorizer_appid: $scope.wxappid,
                                        wxfile: file,
                                        token: token
                                    };
                                    if ($scope.type == 'sucai') {
                                        data.media_type = 'image'
                                    }
                                    if ($scope.type == 'voice') {
                                        data.media_type = 'voice'
                                    }
                                    console.log("data", data, url); // https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN
                                    file.upload = Upload.upload({
                                        url: url,
                                        data: data
                                    });

                                    file.upload.then(function(response) {
                                        $timeout(function() {
                                            // console.log('response:', response.data);
                                            file.result = response.data;
                                            if (response.data.media_id) {
                                                if ($scope.callBack) {
                                                    $scope.callBack();
                                                }

                                            } else if (response.data.url) {

                                                var sessionUrls = sessionService.get($scope.wxappid + "wxurl");
                                                if (sessionUrls) {
                                                    sessionUrls.push({
                                                        url: response.data.url
                                                    });
                                                } else {
                                                    sessionUrls = [{
                                                        url: response.data.url
                                                    }];
                                                }
                                                sessionService.put($scope.wxappid + "wxurl", sessionUrls);

                                                if ($scope.callBack) {
                                                    $scope.callBack({
                                                        url: response.data.url
                                                    });
                                                }

                                            } else {
                                                helper.myAlert("error" + response.data.Msg);
                                            }
                                        });
                                    }, function(response) {
                                        if (response.status > 0)
                                            $scope.errorMsg = response.status + ': ' + response.data;
                                    }, function(evt) {
                                        // Math.min is to fix IE which reports 200% sometimes
                                        file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
                                    });
                                }
                            }
                        });

                    }
                ]
            }
        })
        .directive('uploaderpem', ['dataService', '$compile', 'moment', 'helper', function(dataService, $compile, moment, helper) {
            return {
                restrict: 'E',
                require: 'ngModel',
                replace: true,
                scope: {
                    ngModel: '=',
                },
                // template: '<span> <input type="file" ngf-select ng-model="picFile" name="file" a ngf-model-invalid="errorFile" ngf-keep="distinct" >  <button type="button" class="sui-btn btn-small btn-primary" ng-click="update()">{{"选择"|translate}}</button></span>',
                template: '<span> <input type="file" ngf-select ng-model="picFile" name="file" a ngf-model-invalid="errorFile" ngf-keep="distinct" ng-change="update()" > </span>',
                controller: ['$templateCache', '$rootScope', '$scope', '$timeout', function($templateCache, $rootScope, $scope, $timeout) {

                    $scope.update = function() {
                        if ($scope.picFile) {
                            // console.error("1111eeeeeeeeeeeeeeee", $scope.picFile);
                            var reader = new FileReader();
                            reader.readAsText($scope.picFile);
                            reader.onload = function(e) {
                                $scope.ngModel = e.target.result;
                                // console.error("1111eeeeeeeeeeeeeeee",$scope.ngModel  );
                            };
                        }

                    }


                }],
                link: function(scope, element, attrs, ctrl) {

                }
            }
        }])
})();